package com.example.databindingtest.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.databindingtest.domain.OnSellItem
import com.example.databindingtest.repository.OnSellRepository
import com.example.databindingtest.utils.LoadState
import kotlinx.coroutines.launch

class OnSellViewModel : ViewModel() {

    companion object {
        const val DEFAULT_PAGE = 1
    }

    private var mCurrentPage = DEFAULT_PAGE

    private val repository by lazy {
        OnSellRepository()
    }

    fun loadData() {
        //这个加载是需要ui层转圈圈（Loading）
        //更新这个状态
        loadState.value = LoadState.LOADING
        //加载第一页的数据
        loadDataByPage(mCurrentPage)
    }

    private fun loadDataByPage(mCurrentPage: Int) {
        //根据页面加载数据
        viewModelScope.launch {
            try {
                val result = repository.getOnSellListByPage(mCurrentPage)
                //对数据进行判断：有可能数据为空，有可能数据请求出错
                val resultList = result.data.tbk_dg_optimus_material_response.result_list.map_data
                if (resultList.isEmpty()) {
                    loadState.value = LoadState.EMPTY
                } else {
                    //处理一下数据
                    loadState.value = LoadState.SUCCESS
                    //更新数据
                    contentList.value = resultList
                }

            } catch (e: Exception) {
                loadState.value = LoadState.ERROR
            }
        }
    }

    //所关心的数据
    //加载状态：Loading,Success,Empty,Error,None
    val loadState by lazy {
        MutableLiveData<LoadState>()
    }

    //数据列表：contentList
    val contentList by lazy {
        MutableLiveData<MutableList<OnSellItem>>()
    }
}